package com.school.graduation.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.school.graduation.R;
import com.school.graduation.bean.SignCallBack;
import com.school.graduation.common.base.BaseActivity;
import com.school.graduation.internet.SignInterface;
import com.school.graduation.util.Located;
import com.school.graduation.util.ToastUtil;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;

public class SignUpActivity extends BaseActivity implements View.OnTouchListener{
    public static final int SIGN_UP_ERROR = -1;
    public static final int SIGN_UP_SUCCESS = 0;
    public static final int SIGN_UP_ALREADY_EXISTS = 1;

    @Bind(R.id.sign_up_name)
    EditText signUpName;
    @Bind(R.id.sign_up_password)
    EditText signUpPassword;
    @Bind(R.id.sign_up_email)
    EditText signUpEmail;
    @Bind(R.id.sign_up_city)
    EditText signUpCity;
    @Bind(R.id.sign_up_button)
    TextView signUpButton;
    @Bind(R.id.sign_in_layout)
    RelativeLayout signInLayout;

    private boolean inputEmpty = false;
    private String address;
    private double latitude;
    private double longitude;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private Intent returnIntent;

    @Override
    public int getContentView() {
        return R.layout.activity_sign_up;
    }

    @Override
    public void initData() {
        returnIntent = new Intent();
        keepSignUpBtOver();
        setEditTouchListener();
        Located();
        initSp();
    }

    private void initSp() {
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void keepSignUpBtOver() {
        signInLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                signInLayout.getWindowVisibleDisplayFrame(rect);
                int layoutInvisibleHeight = signInLayout.getRootView().getHeight() - rect.bottom;
                if (layoutInvisibleHeight>=200){
                    int scrollHeight = layoutInvisibleHeight - (signInLayout.getMeasuredHeight()-signUpButton.getBottom());
                    if (scrollHeight>0) signInLayout.scrollTo(0,scrollHeight);
                }else signInLayout.scrollTo(0,0);
            }
        });
    }

    private void setEditTouchListener() {
        signUpName.setOnTouchListener(this);
        signUpPassword.setOnTouchListener(this);
        signUpEmail.setOnTouchListener(this);
        signUpCity.setOnTouchListener(this);
    }


    @OnClick({ R.id.sign_up_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sign_up_button:
                signUpUser();
                break;
        }
    }

    private void signUpUser() {
        final String name = signUpName.getText().toString();
        final String password = signUpPassword.getText().toString();
        returnIntent.putExtra("name",name);
        returnIntent.putExtra("password",password);
        String email = signUpEmail.getText().toString();
        String city = signUpCity.getText().toString();
        checkInput(name);
        checkInput(password);
        checkInput(email);
        checkInput(city);
        if (!inputEmpty) {
            signUp(name,password,email,city);
        }
    }

    private void signUp(String name, final String password, String email, String city) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://123.206.20.29:3000/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        SignInterface signInterface = retrofit.create(SignInterface.class);
        Call<SignCallBack> signUpCall = signInterface.signUp(name,password,email,city);
        signUpCall.enqueue(new Callback<SignCallBack>() {
            @Override
            public void onResponse(Call<SignCallBack> call, Response<SignCallBack> response) {
                if (response.isSuccessful()){
                    SharedPreferences sp = getApplicationContext().getSharedPreferences("user_cache", Context.MODE_MULTI_PROCESS |
                            Activity.MODE_WORLD_WRITEABLE);
                    editor = sp.edit();
                    SignCallBack callBack = response.body();
                    editor.putString("password",password);
                    editor.commit();
                    afterSignup(callBack);
                }
            }

            @Override
            public void onFailure(Call<SignCallBack> call, Throwable t) {
                ToastUtil.makeShortToast(context,"error:"+t.toString());
            }
        });
    }

    private void afterSignup(SignCallBack callBack) {
        int user = callBack.getUser();
        switch (user){
            case SIGN_UP_ERROR:
            case SIGN_UP_ALREADY_EXISTS:
                ToastUtil.makeShortToast(context,callBack.getStatus());
                break;
            case SIGN_UP_SUCCESS:
                ToastUtil.makeShortToast(context,callBack.getStatus());
                SignCallBack.DataBean dataBean = callBack.getData();
                SharedPreferences sp = getApplicationContext().getSharedPreferences("user_cache", Context.MODE_MULTI_PROCESS |
                        Activity.MODE_WORLD_WRITEABLE);
                editor = sp.edit();
                editor.putString("name",dataBean.getName());
                editor.putString("id",dataBean.get_id());
                editor.putString("city",dataBean.getCity());
                editor.apply();
                setResult(RESULT_OK,returnIntent);
                finish();
                break;
        }
    }

    private void checkInput(String input) {
        if ("".equals(input)) {
            ToastUtil.makeShortToast(context,"注册信息不能为空");
            inputEmpty = true;
            return;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()){
            case R.id.sign_up_name:
                setAllEditHint();
                signUpName.setHint("");
                signUpName.setCursorVisible(true);
                break;
            case R.id.sign_up_password:
                setAllEditHint();
                signUpPassword.setHint("");
                signUpPassword.setCursorVisible(true);
                break;
            case R.id.sign_up_email:
                setAllEditHint();
                signUpEmail.setHint("");
                signUpEmail.setCursorVisible(true);
                break;
            case R.id.sign_up_city:
                setAllEditHint();
                signUpCity.setHint("");
                signUpCity.setCursorVisible(true);
                break;
        }
        return false;
    }

    private void setAllEditHint() {
        signUpName.setHint("Name or Surname");
        signUpPassword.setHint("Password");
        signUpEmail.setHint("Email");
        signUpCity.setHint("City");
    }

    private void Located(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && this.checkSelfPermission(ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED
                &&this.checkSelfPermission(ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION},0);
        }
        Located located = new Located(context);
        located.starLocated(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation!= null){
                    if (aMapLocation.getErrorCode() == 0){
                        address = aMapLocation.getProvince();
                        latitude = aMapLocation.getLatitude();
                        longitude = aMapLocation.getLongitude();
                        signUpCity.setText(address);
                        Log.e("signUp",address);
                    }else {
                        Log.e("AmapError","location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });

    }
}
